/*
 * @Author: weisheng
 * @Date: 2024-11-18 15:17:38
 * @LastEditTime: 2024-11-18 15:20:06
 * @LastEditors: weisheng
 * @Description:
 * @FilePath: /wot-demo/src/router/index.ts
 * 记得注释
 */
/// <reference types="@uni-helper/vite-plugin-uni-pages/client" />
import { createRouter } from 'uni-mini-router'
import { pages, subPackages } from 'virtual:uni-pages'

interface RouteConfig {
  path: string
  name?: string
  meta?: Record<string, any>
}

// 处理路由配置
function generateRoutes(): RouteConfig[] {
  const routes = pages.map((page) => {
    const { path, name, style = {}, type, layout, ...rest } = page
    return {
      path: `/${path}`,
      name: name || path.replace(/\//g, '-'),
      meta: {
        title: style.navigationBarTitleText,
        type,
        layout,
        ...rest,
      },
    }
  })

  if (subPackages && subPackages.length > 0) {
    subPackages.forEach((subPackage) => {
      const subRoutes = subPackage.pages.map((page: any) => {
        const { path, name, style = {}, type, layout, ...rest } = page
        return {
          path: `/${subPackage.root}/${path}`,
          name: name || `${subPackage.root}-${path}`.replace(/\//g, '-'),
          meta: {
            title: style.navigationBarTitleText,
            type,
            layout,
            ...rest,
          },
        }
      })
      routes.push(...subRoutes)
    })
  }

  return routes
}

// 创建路由实例
const router = createRouter({
  routes: generateRoutes(),
})

// 初始化路由对象
router.beforeEach((to, from, next) => {
  // 初始化路由对象
  if (!to.query) {
    to.query = {}
  }
  if (!from.query) {
    from.query = {}
  }
  if (!to.params) {
    to.params = {}
  }
  if (!from.params) {
    from.params = {}
  }

  console.log('[Router] beforeEach', { to, from })
  next()
})

router.afterEach((to, from) => {
  console.log('[Router] afterEach', { to, from })
})

export default router
